package com.kuang.gulimall.cart.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kuang.common.utils.R;
import com.kuang.gulimall.cart.feign.ProductFeignService;
import com.kuang.gulimall.cart.interceptor.CartInterceptor;
import com.kuang.gulimall.cart.vo.CartItemVo;
import com.kuang.gulimall.cart.vo.CartVo;
import com.kuang.gulimall.cart.vo.SkuInfoVo;
import com.kuang.gulimall.cart.vo.UserInfoTo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    /**添加到购物车
     *
     * @param skuId
     * @param num
     * @return
     */
    @SneakyThrows
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) {

        //1,是否登录？，登录过的购物车是ok的，没登陆的购物车应该先登录
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //先判断skuid去重
        String res = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = new CartItemVo();
        if (StringUtils.isEmpty(res)){
            //购物车没有这个商品

            //2，将商品添加新商品到购物车
            //第一个异步任务
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(()->{
                //1，远程查询当前要添加的商品的信息
                R info = productFeignService.info(skuId);
                SkuInfoVo data = (SkuInfoVo) info.getmyData("skuInfo", new TypeReference<SkuInfoVo>() {});

                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(data.getSkuDefaultImg());
                cartItemVo.setTitle(data.getSkuTitle());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setPrice(data.getPrice());
            },executor);

            //2，远程查询组合信息，这里用多线程的方式同时查询 ,run关心返回值，supply不关心返回值
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(skuSaleAttrValues);
            }, executor);

            //这个地方有个大坑，这里用异步任务之后，一定要判断逻辑，是先结束，后写入redis，这里数据转换异常是空数据序列化写入redis
            //3，让redis操作，提前序列化，避免redis自己默认使用jdk序列化
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;

        }else{
            //购物车有此商品，修改数量即可
            CartItemVo cartItemVo1 = JSON.parseObject(res, CartItemVo.class);
            cartItemVo1.setCount(cartItemVo1.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo1));
            return cartItemVo1;
        }
    }

    /**获取购物车对象
     *
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(o, CartItemVo.class);
        return cartItemVo;
    }

    /**获取购物车
     *
     * @return
     */
    @Override
    public CartVo getCart() {

        CartVo cart = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){

            //1，登录用户，合并购物车
            String cartKey =CART_PREFIX+ userInfoTo.getUserId();

            //临时购物车的键
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();

            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
            //2，判断是否有临时购物车数据
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null){
                //临时购物车有数据，需要合并
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清除临时购物车
                clearCart(tempCartKey);
            }
            //3，获取登录后的购物车数据,包含合并过来的临时购物车数据，和登录后的购物车数据
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        }else {
            //2，没登录
            String cartKey =CART_PREFIX+ userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }

        return cart;

    }

    /**清除购物车
     *
     * @param cartkey
     */
    @Override
    public void clearCart(String cartkey) {
        redisTemplate.delete(cartkey);
    }




    /**获取我们要操作的购物车
     *
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null && values.size()>0){
            List<CartItemVo> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**与redis操作
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId()!=null){
            //登录购物车
            cartKey = CART_PREFIX+userInfoTo.getUserId();

        }else {
            //临时购物车的身份标识，userkey
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }

//        redisTemplate.opsForHash().get(cartKey,"1");
        //绑定hash操作
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    /**web端的cart.html的增删改查
     *
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long deleteId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(deleteId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItems = getCartItems(cartKey);

            //获取所有被选中的购物项
            // 价格要实时查询。
            List<CartItemVo> collect = cartItems.stream()
                    .filter(item -> item.getCheck())
                    .map(item ->{
                        //查询最新价格
                        item.setPrice(productFeignService.getPrice(item.getSkuId()));
                        return item;
                    })
                    .collect(Collectors.toList());


            return collect;
        }

    }
}
